import 'package:aichat_flutter_wallet/module/module_wallet/provider/wallet_index_provider.dart';
import 'package:aichat_flutter_wallet/module/module_wallet_manage/pages/destroy_success_page.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_api.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/utils/auth.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/bottom_sheet_widget.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_network/http_config.dart';
import 'package:lib_network/http_manager.dart';
import 'package:lib_util/lib_util.dart';

import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/mpc_help/mpcManager.dart';
import '../../../module_common/network/http_chain_list.dart';
import '../../../module_common/widgets/dialog/kai_bottom_cloud_dialog.dart';
import '../../module_wallet/widgets/sheet/confirm_alert.dart';

class DeleteWallet extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _DeleteWalletState();
  }
}

class _DeleteWalletState extends State<DeleteWallet> {
  TextEditingController controller = TextEditingController();
  FocusNode focusNode = FocusNode();

  // 云端 分片 暂存本地
  String cloudPiece = '';
  bool isPass = false;

  // 是否坚持 删除钱包
  bool isInsist = false;

  //是否正在展示loading框
  bool _isLoading = false;
  DateTime _startTime = DateTime.now();

  @override
  void initState() {
    super.initState();
  }

  Future<void> doHttpDelete(value) async {
    try {
      var resp = await HttpManager().get(API.walletEscape, {"wallet_id": '1'});
      // 成功
      if (resp?.code == HttpConfig().successCode) {
        int walletId = context.read<WalletInfoNotifier>().walletId;
        if (walletId != 0) {
          if (ObjectBox().deleteWallet(walletId)) {
            // 重置盐  以便于下次 生成钱包 使用
            // var localSalt = await SP().getRandomSalt();
            // if (localSalt != null) {
            //   await SP().setRandomSalt(SP().generateRandomSalt());
            // }
          } else {
            Toast.show(context, message: 'Destruction failed', status: '2');
            return;
          }
        }
        context.read<WalletIndexProvider>().updateInfo();
        Toast.show(context,
            status: '1',
            position: Dpositon.top,
            message: 'Destruction successful',
            duration: Duration(milliseconds: 3000));
        Future.delayed(Duration(microseconds: 3000), () {
          Navigator.of(context).pop();
          Navigator.of(context).push(MaterialPageRoute(
              builder: (_) {
                return DestroySuccessPage(parseMap: value);
              },
              maintainState: false));
        });
      } else {
        Toast.show(context,
            status: '0',
            position: Dpositon.top,
            message: 'Destruction failed',
            duration: Duration(milliseconds: 2000));
      }
    } catch (e) {
      // 失败
      Toast.show(context,
          status: '0',
          position: Dpositon.top,
          message: 'Destruction failed',
          duration: Duration(milliseconds: 2000));
    } finally {
      _hideLoading();
    }
  }

  deleteWallet() async {
    // _showLoading();
    if (controller.text.length == 0) return;
    //I confirm i want to destroy this MPC wallet
    if (controller.text != 'I confirm i want to destroy this MPC wallet')
      return Toast.show(context,
          status: '2',
          position: Dpositon.top,
          message: 'Incorrect input for verification',
          duration: Duration(milliseconds: 2000));
    // 判断没 设置密码
    bool isSetPass = ObjectBox()
        .userSettingsModel
        .isPasswordSet(NativeChannelBridge.instance.appCommMsg!.userId);
    if (!isSetPass) {
      // 关闭当前 页面
      Toast.show(context,
          status: '2',
          message: 'Please set a password first',
          position: Dpositon.top);
      return;
    }
    if (!isPass) {
      isPass = await Authentication().startLocalAuth(
          showPasswordError: false,
          callBackError: () {
            Toast.show(context,
                status: '0',
                position: Dpositon.top,
                message: "Verification password error",
                duration: Duration(milliseconds: 3000));
          });
    }
    if (!isPass) return;
    _showLoading();
    // 执行删除
    var result = await getParse(context);
    if (result.isEmpty) {
      return;
    }
    doHttpDelete(result);
  }

  List<T> removeDuplicates<T>(List<T> list) {
    Set<T> uniqueSet = Set<T>.from(list);
    List<T> uniqueList = uniqueSet.toList();
    return uniqueList;
  }

  // validate 钱包状态类型
  Future<Map<String, String>> getParse(BuildContext context) async {
    Map<String, String> parseMap = {};
    late String pieceA;
    late String pieceB;
    bool needCheck = false;
    List<String> keyList = WalletCheck.getkeyList();
    Wallet? currentWallet = WalletCheck.getWalletInfo();
    kaiPrint('current wallet type: ${currentWallet!.type}');
    String? googleEmailId =
        NativeChannelBridge.instance.appCommMsg?.google_email;
    String? appleUserId =
        NativeChannelBridge.instance.appCommMsg?.apple_user_id;
    String? serverKey = (await WalletCheck.getServerKey()).$1;
    //  没钱包进不了 这页面  不存在 null
    if (currentWallet.type == 2) {
      if (isInsist == false) {
        // 本地 云端
        kaiPrint('status ： ${(googleEmailId != null || appleUserId != null)}');
        if ((googleEmailId != null || appleUserId != null)) {
          if (cloudPiece.isEmpty) {
            _hideLoading();
            // 弹出 服务云端的 获取
            // 判断 空钱包并提示
            Utils.showBottomSheetDialog(context, KaiBottomCloudDialog(
              Confirm: (value) {
                cloudPiece = value;
                if (value.isEmpty) {
                  showDialog(
                    useSafeArea: false,
                    context: context,
                    builder: (context) {
                      return MyDialog(
                        title: 'Important-Note',
                        detail:
                            'I can\'t get the shards of your Cloud file. Do you want to delete your wallet?',
                        onConfirm: () {
                          Navigator.of(context).pop();
                          isInsist = true;
                          deleteWallet();
                        },
                      );
                    },
                  );
                } else {
                  deleteWallet();
                }
              },
            )).then((value) {
              _hideLoading();
            });
            return {};
          } else {
            //  能 从 云端 拉去 情况下 就能 校验
            int localKeyStatus = await mpcTool().verifyMPCFragment(cloudPiece);
            kaiPrint("localKeyStatus3:${localKeyStatus}");
            if (localKeyStatus != 1) {
              _hideLoading();
              showDialog(
                useSafeArea: false,
                context: context,
                builder: (context) {
                  return MyDialog(
                    title: 'Important-Note',
                    detail:
                        'The current cloud sharding is abnormal. Do you want to insist on deleting the wallet?',
                    onConfirm: () {
                      Navigator.of(context).pop();
                      isInsist = true;
                      deleteWallet();
                    },
                  );
                },
              );
              return {};
            } else {
              Toast.show(context,
                  message: 'Successfully pulled shards from the cloud',
                  status: '1',
                  position: Dpositon.top);
              pieceA = keyList[0];
              pieceB = cloudPiece;
              needCheck = true;
            }
          }
        }
      }
      // 非 观察 就默认 两片以上
      // 获取 服务端的
    }
    else {
      kaiPrint('keyList.length = ${keyList.length}');
      // local + server
      if (keyList.length >= 2) {
        pieceA = keyList[0];
        pieceB = keyList[1].isNotEmpty ? keyList[1] : keyList[2];
        // int localKeyStatus = await mpcTool().verifyMPCFragment(pieceA);
        // int localKeyStatusPieceB = await mpcTool().verifyMPCFragment(pieceB);
        // print('localKeyStatus ${localKeyStatus}');
        // print('localKeyStatusPieceB ${localKeyStatusPieceB}');
        // print('当前的分片 A  ${pieceA}');
        // print('当前的分片 B  ${pieceB}');
        needCheck = true;
      } else {
        pieceA = keyList[0];
        // 本地剩下一片 , 一片 存在 服务端，一片在云端
        // local + server
        kaiPrint('currentWallet.isServerBackUp = ${currentWallet.isServerBackUp}');
        int localKeyStatus = await mpcTool().verifyMPCFragment(serverKey);
        kaiPrint("localKeyStatus:${localKeyStatus}");
        if (localKeyStatus == 1) {
          pieceB = serverKey;
          needCheck = true;
        } else {
          if ((currentWallet.appleFileId != null &&
                  currentWallet.appleFileId!.length > 0) ||
              (currentWallet.googleFileId != null &&
                  currentWallet.googleFileId!.length > 0)) {
            if (isInsist == false) {
              if ((googleEmailId != null || appleUserId != null)) {
                // 本地 云端
                if (cloudPiece.isEmpty) {
                  _hideLoading();
                  // 弹出 服务云端的 获取
                  // 判断 空钱包并提示
                  Utils.showBottomSheetDialog(context, KaiBottomCloudDialog(
                    Confirm: (value) {
                      cloudPiece = value;
                      if (value.isEmpty) {
                        showDialog(
                          useSafeArea: false,
                          context: context,
                          builder: (context) {
                            return MyDialog(
                              title: 'Important-Note',
                              detail:
                                  'I can\'t get the shards of your Cloud file. Do you want to delete your wallet?',
                              onConfirm: () {
                                Navigator.of(context).pop();
                                isInsist = true;
                                deleteWallet();
                              },
                            );
                          },
                        );
                      } else {
                        deleteWallet();
                      }
                    },
                  ));
                  return {};
                } else {
                  //  能 从 云端 拉去 情况下 就能 校验
                  int localKeyStatus =
                      await mpcTool().verifyMPCFragment(cloudPiece);
                  kaiPrint("localKeyStatus2:${localKeyStatus}");
                  if (localKeyStatus != -1) {
                    kaiPrint('cloud status failed code is 3');
                    _hideLoading();
                    showDialog(
                      useSafeArea: false,
                      context: context,
                      builder: (context) {
                        return MyDialog(
                          title: 'Important-Note',
                          detail:
                              'The current cloud sharding is abnormal. Do you want to insist on deleting the wallet?',
                          onConfirm: () {
                            Navigator.of(context).pop();
                            isInsist = true;
                            deleteWallet();
                          },
                        );
                      },
                    );
                    return {};
                  } else {
                    Toast.show(context,
                        message: 'Successfully pulled shards from the cloud',
                        status: '1',
                        position: Dpositon.top);
                    pieceB = cloudPiece;
                    kaiPrint('cloud successfully');
                    needCheck = true;
                  }
                }
              }
            }
          }
        }

        // local + cloud
        //   校验本地那片， server 那片 获取
        // Map<String, String?> walletKeyMap = WalletCheck().walletKeyMap;
        // if (walletKeyMap.isEmpty) {
        //   WalletCheckStatus walletCheckStatus =
        //       await WalletCheck().checkWalletException(checkUpload: false);
        //   walletKeyMap = walletCheckStatus.keyMap;
        // }
        // List list = walletKeyMap.values.toList();
        // List mylist = list.where((e) => e != null && e != '').toList();
        // mylist = removeDuplicates(mylist);
        // if (mylist.length >= 2) {
        //   needCheck = true;
        //   pieceA = mylist[0];
        //   pieceB = mylist[1];
        // } else {
        //   needCheck = false;
        // }
      }
    }
    // String? salt = await SP().getRandomSalt();
    String? salt = await SP().getRandomSalt();
    try{
      kaiPrint('serverKey.isNotEmpty ${serverKey.isNotEmpty}');
      if(serverKey.isNotEmpty){
        salt = await HttpChainList().getSaltByUrl()??'';
      }
      kaiPrint('the last get $salt');
    }catch(e){
      kaiPrint('error status $e');
    }

    // 存在两片以上
    if (needCheck) {
      try {
        kaiPrint(
            'salt length ${salt != null ? (salt.toString().length > 0 ? salt.toString().trim() : '') : ''}');
        escapeResp res = await mpcTool().mpcEscape(
            pieceA,
            pieceB,
            salt != null
                ? (salt.toString().length > 0 ? salt.toString().trim() : '')
                : '');
        kaiPrint('mnemonic===${res.mnemonic}');
        kaiPrint('path===${res.path}');
        parseMap['path'] = res.path;
        parseMap['mnemonic'] = res.mnemonic;
      } catch (e) {
        parseMap['mnemonic'] = '';
        parseMap['path'] = '';
      }
      parseMap['salt'] = salt ?? '\  ';
    } else {
      parseMap['salt'] = salt ?? '\  ';
      parseMap['mnemonic'] = '';
      parseMap['path'] = '';
    }
    kaiPrint("running is here？ ${parseMap['salt']?.length}");
    return parseMap;
  }

  Widget TipItem(text) {
    return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Container(
        width: 4.w,
        height: 4.w,
        margin: EdgeInsets.only(top: 6.w),
        decoration: BoxDecoration(
            color: AppColors.c_868391,
            borderRadius: BorderRadius.all(Radius.circular(4))),
      ),
      SizedBox(width: 6.w),
      Expanded(
        child: Text(
          text,
          softWrap: true,
          style: TextStyle(
              fontSize: 12.sp,
              color: AppColors.c_868391,
              fontWeight: FontWeight.w400,
              height: (16 / 12).w),
        ),
      )
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        BottomSheetWidget(
          title: '',
          expand: false,
          child: Container(
            padding: EdgeInsets.fromLTRB(
                20.w, 0, 20.w, MediaQuery.of(context).padding.bottom),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  height: 3.w,
                ),
                Row(
                  children: [
                    Image.asset(
                      'assets/images/status/warn.png',
                      width: 20.w,
                      height: 20.w,
                    ),
                    SizedBox(
                      width: 7.w,
                    ),
                    Text(
                      'Destroy Wallet',
                      style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: AppColors.c_333333),
                    )
                  ],
                ),
                SizedBox(
                  height: 5.w,
                ),
                Text(
                  'Do you need to destroy this MPC wallet?',
                  textAlign: TextAlign.left,
                  style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w400,
                      color: AppColors.c_333333),
                ),
                SizedBox(
                  height: 15.w,
                ),
                TipItem(
                    "This operation will delete the IPFS shardings of the MPC wallet associated with this account, but it won't affect the local and cloud shardings."),
                SizedBox(
                  height: 15.w,
                ),
                TipItem(
                    "Please make sure you have at least two shardings or have already restored your private key via dual-entropy obfuscation algorithm."),
                SizedBox(
                  height: 25.w,
                ),
                Text(
                  'Please enter:',
                  style: TextStyle(
                      fontSize: 14.sp,
                      color: AppColors.c_333333,
                      fontWeight: FontWeight.w500),
                ),
                SizedBox(
                  height: 3.w,
                ),
                Row(
                  children: [
                    Flexible(
                        child: GestureDetector(
                      child: Text(
                        '"I confirm i want to destroy this MPC wallet"',
                        style: TextStyle(
                            fontSize: 14.sp,
                            color: AppColors.c_F4654D,
                            fontWeight: FontWeight.w500),
                      ),
                      onTap: () {
                        bool isCopySuccess = Utils.copyText(
                            "I confirm i want to destroy this MPC wallet");
                        Toast.show(context,
                            position: Dpositon.top,
                            message: isCopySuccess
                                ? 'Copied successfully'
                                : 'Copy failed',
                            status: isCopySuccess ? '1' : '2');
                      },
                    )),
                  ],
                ),
                SizedBox(
                  height: 10.w,
                ),
                Container(
                    height: 46.w,
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    decoration: BoxDecoration(
                        color: AppColors.c_F6F6F6,
                        borderRadius: BorderRadius.all(Radius.circular(10.w))),
                    child: TextField(
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(
                            RegExp("[a-zA-Z0-9 ]")),
                        // 限制输入长度为20个字符
                      ],
                      keyboardType: TextInputType.text,
                      controller: controller,
                      focusNode: focusNode,
                      onTapOutside: (PointDownEvent) {
                        focusNode.unfocus();
                      },
                      onEditingComplete: () {
                        focusNode.unfocus();
                      },
                      onChanged: (val) {
                        setState(() {});
                      },
                      cursorColor: Color.fromRGBO(134, 103, 254, 1),
                      style: TextStyle(
                        fontSize: 15.sp,
                        height: (20 / 15).w,
                        color: Color.fromRGBO(51, 51, 51, 1),
                        fontWeight: FontWeight.w500,
                      ),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: 'Please enter',
                        hintStyle: TextStyle(
                          fontSize: 14.sp,
                          height: (20 / 14).w,
                          color: Color.fromRGBO(190, 189, 202, 1),
                        ),
                      ),
                      minLines: 1,
                      maxLines: 1,
                    )),
                SizedBox(
                  height: 20.w,
                ),
                Container(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(
                          child: PublicButton(
                              margin: EdgeInsets.zero,
                              type: ButtonType.defaultType,
                              text: 'Cancel',
                              onClick: () {
                                Navigator.of(context).pop();
                              })),
                      SizedBox(
                        width: 20.w,
                      ),
                      Expanded(
                          child: PublicButton(
                        margin: EdgeInsets.zero,
                        type: ButtonType.private,
                        disabledStatus: controller.text.isEmpty,
                        text: 'Comfirm',
                        onClick: deleteWallet,
                      ))
                    ],
                  ),
                ),
                SizedBox(
                  height: MediaQuery.of(context).viewInsets.bottom + 10,
                )
              ],
            ),
          ),
        ),
        loadingWidget()
      ],
    );
  }

//loading展示//////////////
  _showLoading() {
    setState(() {
      _startTime = DateTime.now();
      _isLoading = true;
    });
  }

  Future<void> _hideLoading() async {
    //如果太快的话就延时消失
    var difMilliseconds = DateTime.now().difference(_startTime).inMilliseconds;
    //最少要2秒后才隐藏
    if (2000 - difMilliseconds >= 0) {
      await Future.delayed(Duration(milliseconds: 2000 - difMilliseconds), () {
        if(mounted)
        setState(() {
          _isLoading = false;
        });
      });
    } else {
      if(mounted)
      setState(() {
        _isLoading = false;
      });
    }
  }

  Widget loadingWidget() {
    return Visibility(
      visible: _isLoading,
      child: Positioned(
          left: 0,
          right: 0,
          bottom: 0,
          top: 0,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            color: Colors.transparent,
            child: Center(
              child: Container(
                padding: EdgeInsets.all(14.w),
                decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.8),
                    borderRadius: BorderRadius.all(Radius.circular(12.w))),
                child: Image.asset(
                  'assets/images/common/loading2.gif',
                  width: 60.w,
                  height: 60.w,
                ),
              ),
            ),
          )),
    );
  }
}
